package com.yun.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.blog.bean.Blog;
import com.yun.blog.bean.Result;
import com.yun.blog.bean.dto.BlogDto;
import com.yun.blog.service.BlogService;
import com.yun.blog.utils.FileUtils;
import com.yun.blog.utils.JwtUtils;
import com.yun.blog.utils.QianiuUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * title        : BlogController
 * projectName  : dantouBlog-back
 * description  : TODO
 * author       : simple
 * date         : 2022/11/28下午4:28
 */

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    BlogService blogService;


    /**
     * 搜索
     *
     * @param pageSize   每一页的数据条数
     * @param pageNum    页码
     * @param searchText 搜索关键词
     * @param orderBy    排序
     * @return com.yun.blog.bean.Result
     **/
    @GetMapping("/getBlogs")
    public Result getBlogs(@RequestParam(defaultValue = "10") Integer pageSize,
                           @RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "") String searchText,
                           @RequestParam(defaultValue = "desc") String orderBy
    ) {

        Result success = Result.success();
        // LambdaQueryWrapper<Blog> queryWrapper = Wrappers.lambdaQuery();
        // 如果有查询条件就查询名称一样的
        // if (StringUtils.hasText(searchText)) {
        //     queryWrapper.like(Blog::getBlogTitle, searchText);
        // }
        Page<Blog> page = blogService.customPage(new Page<>(pageNum, pageSize), searchText, orderBy);

        success.add("page", page);
        return success;
    }

    /**
     * 时间线
     *
     * @param pageSize 每页数据条数
     * @param pageNum  页码
     * @return Result
     * @author yun
     * @date 2023/5/5 下午9:59
     */
    @GetMapping("/timeline")
    public Result timeline(@RequestParam(defaultValue = "15") Integer pageSize,
                           @RequestParam(defaultValue = "1") Integer pageNum) {
        try {
            Result success = Result.success();
            Page<Blog> page = blogService.timelinePage(new Page<>(pageNum, pageSize));
            success.add("page", page);
            return success;
        } catch (Exception e) {
            log.error("获取失败：错误信息为：{}", e.getMessage());
            return Result.fail("获取失败：错误信息为：" + e.getMessage());
        }

    }

    /**
     * 条件查询
     * TODO： 需要修改为实体参数查询
     *
     * @param map 条件
     * @return Result
     * @author yun
     * @date 2023/5/5 下午10:02
     */
    @PostMapping("/condition")
    public Result condition(@RequestBody HashMap<String, Object> map) {

        Integer pageSize = (Integer) map.get("pageSize");
        Integer pageNum = (Integer) map.get("pageNum");
        String searchText = (String) map.get("searchText");
        Integer categoryId = (Integer) map.get("categoryId");
        Boolean isTop = (Boolean) map.get("isTop");
        ArrayList<Integer> tagIdList = (ArrayList<Integer>) map.get("tagIdList");
        String beginCreateTime = (String) map.get("beginCreateTime");
        String endCreateTime = (String) map.get("endCreateTime");
        String orderBy = (String) map.get("orderBy");

        try {
            Result success = Result.success();
            Page<Blog> page = blogService.getByCondition(
                    new Page<>(pageNum, pageSize),
                    searchText, categoryId, isTop, tagIdList, beginCreateTime, endCreateTime, orderBy
            );
            success.add("page", page);
            return success;
        } catch (Exception e) {
            log.error("获取失败：错误信息为：{}", e.getMessage());
            return Result.fail("获取失败：错误信息为：" + e.getMessage());
        }

    }

    @GetMapping("/getBlogById")
    public Result getBlogById(Integer id) {
        Blog blog = blogService.getByBlogId(id);
        return Result.success("查询成功！").add("blog", blog);
    }

    @GetMapping("/getBlogByCategoryId")
    public Result getBlogByCategoryId(Integer categoryId) {
        List<Blog> blogs = blogService.listAllByBlogCategoryId(categoryId);
        return Result.success("查询成功！").add("blogs", blogs);
    }

    @GetMapping("/getTopBlogs")
    @Cacheable(value = "blog::topping",key = "'top'")
    public Result getTopBlogs() {
        List<Blog> blogs = blogService.getByIsTop(true);
        return Result.success("查询成功！").add("blogs", blogs);
    }


    @GetMapping("/getBlogByTagId")
    public Result getBlogByTagId(Integer tagId) {
        List<Blog> blogs = blogService.listAllByTagId(tagId);
        return Result.success("查询成功！").add("blogs", blogs);
    }

    @GetMapping("/getNewest")
    @Cacheable(value = "blog::newest", key = "#count")
    public Result getNewest(@RequestParam(defaultValue = "10") Integer count) {
        List<Blog> blogs = blogService.getNewBlogByCount(count);
        return Result.success("查询成功！").add("blogs", blogs);
    }

    @GetMapping("/deleteBlog")
    @CacheEvict(value = "blog", key = "#blogId", allEntries = false, beforeInvocation = true)
    public Result deleteBlog(Integer blogId) {
        blogService.removeById(blogId);
        return Result.success("删除成功！");
    }

    @GetMapping("/addBlogViews")
    public Result addBlogViews(Integer blogId) {
        blogService.addBlogViews(blogId);
        return Result.success("增加阅读量成功！");
    }


    @PostMapping("/save")
    @CacheEvict(value = {"blog::newest", "blog::topping"}, allEntries = true)
    public Result save(@RequestBody BlogDto blogDto, HttpServletRequest request) {
        // 设置作者为当前登录的用户
        blogDto.setAuthorId(JwtUtils.getMemberIdByToken(request));
        Blog blog1 = blogService.saveOrUpdate(blogDto);
        // 要给前端返回一个id，下次传递过来就可以修改
        return Result.success("保存成功！").add("id", blog1.getBlogId());
    }

    @PostMapping("/uploadImg")
    public Result uploadIcon(MultipartFile Img) {
        Result fail = Result.fail();
        if (Img == null || Img.isEmpty()) {
            fail.setMsg("图片不能为空！");
            return fail;
        }
        String filename = Img.getOriginalFilename();
        boolean allowPic = FileUtils.isAllowPic(filename);
        if (!allowPic) {
            fail.setMsg("图片类型不正确！");
            return fail;
        }

        try {
            LocalDate now = LocalDate.now();
            String date = String.format("%d-%d-%d", now.getYear(), now.getMonthValue(), now.getDayOfMonth());
            // String imgPath = saveImg(Img, "blog/" + date);
            String imgPath = QianiuUploadUtils.upload(Img, "blog/" + date);
            Result success = Result.success("图片保存成功！");
            success.add("imgPath", imgPath);
            return success;
        } catch (Exception e) {
            log.error("图片保存失败！，错误信息为：{}", e.getMessage());
            fail.setMsg("图片保存失败！，错误信息为：" + e.getMessage());
            return fail;
        }
    }

    @GetMapping("/getViewRankTop10")
    public Result getViewRankTop10() {
        List<Blog> viewRank = blogService.getViewRank(10);
        Result success = Result.success();
        success.add("blogs", viewRank);
        return success;
    }

    @GetMapping("/getPreviousAndNext")
    public Result getPreviousAndNext(Integer blogId){
        Result success = Result.success();
        success.add("previous",blogService.getPrevious(blogId));
        success.add("next",blogService.getNext(blogId));
        return success;
    }
}
